﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CommonShop.Service.Helper;

namespace CommonShop.Web.Controllers
{
    public class ToolsController : Controller
    {
        //
        // GET: /Tools/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Weather() {
            return View();
        }

        [HttpPost]
        public ActionResult Weather(FormCollection values)
        {
            var name =  values["City"].ToString();
            //ViewBag.City = name;

            string url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";
            string methodName = "getWeatherbyCityName";
            object[] args = new object[1];
            args[0] = name;

            String[] str = WebServiceHelper.InvokeMethod<String[]>(url, methodName, args);

            ViewBag.Today = str[5];
            ViewBag.Tommo = str[12];
            ViewBag.Three = str[17];

            //for (int i = 6; i < str.Length + 6; i++) {

            //    ViewBag[i] = str[i - 6].ToString();
            //}

            return View("Result", ViewBag);
        }


        public ActionResult Calculate()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Calculate(FormCollection values)
        {
            var zonge =  values["Zonge"];
            var shoufu = values["Shoufu"];
            ViewBag.PayPermonth = GetPayPerMonth(decimal.Parse(zonge), decimal.Parse(shoufu), decimal.Parse((0.0470 / 12).ToString()));
            return View(values);
        }

        public ActionResult CreateDB() {
            var factory = NHibernateHelper.CreateSessionFactory();
            return View();
        }

        #region 计算辅助方法
        /// <summary>
        /// 等额本金计算每月还款
        /// </summary>
        /// <param name="zonge">贷款总额</param>
        /// <param name="shoufu">首付款</param>
        /// <param name="sale">利率</param>
        /// <returns>每月还款额</returns>
        private decimal GetPayPerMonth(decimal zonge, decimal shoufu, decimal sale) {
            decimal permonth = 0m;
            decimal PayLast = zonge - shoufu;


            decimal year = 20M;
            double temp = System.Math.Pow((1 + Convert.ToDouble( sale)), Convert.ToDouble(year * 12));
            permonth = Math.Round(((PayLast * sale * Convert.ToDecimal(temp)) / (Convert.ToDecimal(temp) - 1)), 1);

            return permonth;



        }
        #endregion
    }
}
